/**
 * 隐患上报 编辑页
 *
 * 作者 wanghw
 * 日期 2024-08-20 09:23:04
 */
layui.use(['jquery', 'febs', 'form', 'validate', 'fileUpload', 'fileUpload', 'autocomplete', 'commonJS', 'laydate'], function () {
    var $ = layui.$,
        febs = layui.febs,
        layer = layui.layer,
        form = layui.form,
        $view = $('#hazardReportRectification-edit'),
        $unsafeName = $view.find('#unsafeName'),
        // $userManage = $('#userManage'),
        $forwardToUserManage = $('#forwardToUserManage'),
        fileUpload = layui.fileUpload,
        autocomplete = layui.autocomplete,
        commonJS = layui.commonJS,
        laydate = layui.laydate,
        validate = layui.validate;

    form.verify(validate);
    form.render();

    initDate();
    initImg();
    initFormValue();


    function initDate() {
        laydate.render({
            elem: "#rectificationDate",
            type: 'datetime',
            value: new Date(),
            btns: ['now', 'confirm']

        })
    }

    function initFormValue() {
        if (hazardReport.feedbackContent) {
            form.val("hazardReportRectification-edit-form", {
                "feedbackContent": hazardReport.feedbackContent,
            });
        }
        if (hazardReport.status && hazardReport.status == '4') {
            form.val("hazardReportRectification-edit-form", {
                "status": hazardReport.status,
            });
        }
        if (hazardReport.feedBackFileList) {
            form.val("hazardReportRectification-edit-form", {
                "status": hazardReport.status,
            });
        }

        febs.initDictItemLabel($unsafeName, 'SAFETY_HAZARD_UNSAFE_FORM', hazardReport.unsafeName);

        initDetailTale();

    }


    form.on('submit(hazardReportRectification-edit-form-submit)', function (data) {
        var fileList = getImgData();
        if(data.field.status === '5' && commonJS.isEmpty(fileList)){
            febs.alert.warn('整改图片不能为空！');
            return false;
        }

        data.field.feedBackFileList = fileList;
        if (data.field.status === '12') {
            data.field.rectificationMeasures = data.field.auditReason;
        }
        addOrUpdate(data.field);
        return false;
    });

    function initImg() {
        var fileUploadDiv = fileUpload.render({
            elem: '#imgView',
            type: 0,//0-图片，1-视频，2-其他
            maxNum: 5,
            defaultData: getFileList(),
            isDetail: true,
            done: function (res) {
            },
        });

        var fileUploadDiv1 = fileUpload.render({
            elem: '#fileUpload',
            url: ctx + 'hazard/upload',
            type: 0,//0-图片，1-视频，2-其他
            maxNum: 5,
            defaultData: getFileList2(),
            done: function (res) {
            },
        });
    }

    function getFileList() {
        if (hazardReport && hazardReport.fileList) {
            return hazardReport.fileList
        } else {
            return []
        }
    }

    function getFileList2() {
        if (hazardReport && hazardReport.feedBackFileList) {
            return hazardReport.feedBackFileList
        } else {
            return []
        }
    }

    function addOrUpdate(data) {

        if (data.status === '4') {
            febs.modal.confirm('保存整改信息', '确定保存信息？', function () {
                febs.postArray(ctx + 'saveHazardReportRectification', data, function () {
                    layer.closeAll();
                    febs.alert.success('保存成功');
                    $('#febs-hazardReportRectification').find('#query').trigger('click');
                });
            });

        } else if (data.status === '2') {
            febs.modal.confirm('转发整改信息', '确定转发信息？', function () {
                febs.postArray(ctx + 'forwardToHazardReportRectification', data, function () {
                    layer.closeAll();
                    febs.alert.success('转发成功');
                    $('#febs-hazardReportRectification').find('#query').trigger('click');
                });
            });


        } else {
            febs.modal.confirm('提交整改信息', '确定提交信息？', function () {
                febs.postArray(ctx + 'submitHazardReportRectification', data, function () {
                    layer.closeAll();
                    febs.alert.success('提交成功');
                    $('#febs-hazardReportRectification').find('#query').trigger('click');
                });
            });


        }


    }


    form.on('radio(rectificationStatus)', function (obj) {
        if (obj.value === '5' || obj.value === '4') {
            //整改
            $('#rectification').removeClass('febs-hide');
            $('#reback').addClass('febs-hide');
            $('#forwardTo').addClass('febs-hide');
            $view.find('textarea[name="auditReason"]').attr("lay-verify", "");
            $view.find('textarea[name="feedbackContent"]').attr("lay-verify", "required");
            $view.find('input[name="forwardToUserName"]').attr("lay-verify", "required");
            $view.find('input[name="forwardToUserName"]').attr("lay-verify", "");
            clearForwardTo();
        } else if (obj.value === '12') {
            //制定退回
            $('#rectification').addClass('febs-hide');
            $('#forwardTo').addClass('febs-hide');
            $('#reback').removeClass('febs-hide');
            $view.find('textarea[name="auditReason"]').attr("lay-verify", "required")
            $view.find('textarea[name="feedbackContent"]').attr("lay-verify", "")
            $view.find('input[name="forwardToUserName"]').attr("lay-verify", "");
            clearForwardTo()
        } else if (obj.value === '2') {
            //制定退回
            $('#rectification').addClass('febs-hide');
            $('#reback').addClass('febs-hide');
            $('#forwardTo').removeClass('febs-hide');
            $view.find('input[name="forwardToUserName"]').attr("lay-verify", "required");
            $view.find('textarea[name="feedbackContent"]').attr("lay-verify", "");
            $view.find('textarea[name="auditReason"]').attr("lay-verify", "");
        }

    })


    function getImgData() {
        var imgDatas = $view.find('#rectification').find(".imgOne")
        var imgList = [];
        $.each(imgDatas, function (index, item) {
            var data = {
                filePath: item.dataset.filepath,
                fileName: item.dataset.filename,
                smallPath: item.dataset.smallpath,
            }
            imgList.push(data);
        })
        return imgList;
    }

    $forwardToUserManage.on('click', function () {
        febs.modal.open('转发对象选择', 'common/user', {
            btn: ['确认', '关闭'],
            area: $(window).width() <= 750 ? ['95%', '85%'] : ['80%', '85%'],
            data: {
                tenantId: getTenantId(),
                multiple: false,
            },
            yes: function (index, layero) {
                let selectData = null
                if (typeof getSelectData === 'function') {
                    selectData = getSelectData()
                }
                $view.find("input[name=forwardToUserName]").val(selectData.uname);
                $view.find("input[name=forwardToUserId]").val(selectData.userId);
                $view.find("input[name=forwardToUserNo]").val(selectData.userNo);
                $view.find("input[name=forwardToUserDeptId]").val(selectData.deptId);
                $view.find("input[name=forwardToUserDeptName]").val(selectData.deptName);
                $('#deptName').text(selectData.deptName);
                $('#leaderNo').text(selectData.userNo);
                layer.close(index);
            },
            btn2: function (index, layero) {
                layer.close(index);
                return false;
            }
        });
    });

    $('#forwardToInputAuto').autocomplete({
        serviceUrl: ctx + 'common/user/list',//测试接口
        paramName: 'keywords',
        useType: 'user',
        params: {tenantId: getTenantId()},
        onSelect: function (suggestion) {
            $view.find("input[name=forwardToUserName]").val(suggestion.value);
            $view.find("input[name=forwardToUserId]").val(suggestion.data);
            $view.find("input[name=forwardToUserNo]").val(suggestion.userNo);
            $view.find("input[name=forwardToUserDeptId]").val(suggestion.deptId);
            $view.find("input[name=forwardToUserDeptName]").val(suggestion.deptName);
            $('#deptName').text(suggestion.deptName);
            $('#leaderNo').text(suggestion.userNo);
        },
    });

    function getTenantId() {
        if (hazardReport) {
            return hazardReport.tenantId;
        } else {
            return POPUP_DATA.tenantId;
        }
    }

    function clearForwardTo() {
        $view.find("input[name=forwardToUserName]").val('');
        $view.find("input[name=forwardToUserId]").val('');
        $view.find("input[name=forwardToUserNo]").val('');
        $view.find("input[name=forwardToUserDeptId]").val('');
        $view.find("input[name=forwardToUserDeptName]").val('');
    }

    function initDetailTale(){
        if(hazardReport.planRecordList){
            planTableIns = febs.table.init({
                elem: $view.find('table[id="hazardReportPlanRecordTable"]'),
                id: 'hazardReportPlanRecordTable',
                page:false,
                skin: '',
                limit:Number.MAX_VALUE,
                cols: [
                    [
                        {type: 'numbers',title:'序号'},
                        {field: 'auditRealName', title: '制定人姓名',  width: 120},
                        {
                            field: 'auditResult', title: '制定结果', width: 100, align: 'center', templet: function (d) {
                                if (d.auditResult == '1') {
                                    return '<span class="layui-badge febs-tag-green">通过</span>';
                                } else {
                                    return '<span class="layui-badge febs-tag-magenta">退回</span>';
                                }
                            }
                        },
                        {field: 'createdTime', title: '制定时间', width: 160,align:'center'},
                        {field: 'auditReason', title: '制定理由', minWidth: 120 }
                    ]
                ],
                data:hazardReport.planRecordList
            });
        }

        if(hazardReport.feedBackRecordList){
            feedBackTableIns = febs.table.init({
                elem: $view.find('table[id="hazardReportFeedBackRecordTable"]'),
                id: 'hazardReportFeedBackRecordTable',
                page:false,
                skin: '',
                limit:Number.MAX_VALUE,
                cols: [
                    [
                        {type: 'numbers',title:'序号'},
                        {field: 'auditRealName', title: '反馈人姓名',  width: 120},
                        {
                            field: 'auditResult', title: '反馈结果', width: 100, align: 'center', templet: function (d) {
                                if (d.auditResult == '1') {
                                    return '<span class="layui-badge febs-tag-green">通过</span>';
                                } else {
                                    return '<span class="layui-badge febs-tag-magenta">退回</span>';
                                }
                            }
                        },
                        {field: 'createdTime', title: '反馈时间', width: 160,align:'center'},
                        {field: 'auditReason', title: '反馈理由', minWidth: 120 },
                    ]
                ],
                data:hazardReport.feedBackRecordList
            });
        }

        if(hazardReport.auditRecordList){
            feedBackTableIns = febs.table.init({
                elem: $view.find('table[id="hazardReportAuditRecordTable"]'),
                id: 'hazardReportAuditRecordTable',
                page:false,
                skin: '',
                limit:Number.MAX_VALUE,
                cols: [
                    [
                        {type: 'numbers',title:'序号'},
                        {field: 'auditRealName', title: '审核人姓名', width: 120},
                        {
                            field: 'auditResult', title: '审核结果', width: 100, align: 'center', templet: function (d) {
                                if (d.auditResult == '1') {
                                    return '<span class="layui-badge febs-tag-green">审核通过</span>';
                                } else {
                                    return '<span class="layui-badge febs-tag-magenta">审核退回</span>';
                                }
                            }
                        },

                        {field: 'auditReason', title: '审核理由', minWidth: 120 },
                        {field: 'createdTime', title: '审核时间', width: 160,align:'center'},
                    ]
                ],
                data:hazardReport.auditRecordList
            });
        }
        form.render()
    }

});